import React from "react";
import {FlatList, TouchableOpacity, View} from "react-native";

import ModalPicker from '../components/ModalPicker';
import BookItem from "../components/BookItem";
import SearchInput from "../components/SearchInput";
import ctx, {apis} from '../apis/';
import LoadingUtil from "../utils/LoadingUtil";
import Toast from "../components/Toast/";
import MyLoading from "../components/MyLoading";
import {MyStatusBar} from "../components/MyStatusBar";

import withErrorBoundary from '../with_error_boundary.js';

class SearchScreen extends React.Component {
    constructor(props) {
        super(props);

        let apiArray = Object.keys(apis).map(key => apis[key]);
        let apiPickerData = [];
        if (apiArray.length > 0) {
            apiPickerData.push({key: '', section: true, label: '请选择小说源'});
            for (let i in apiArray) {
                let each = apiArray[i];
                apiPickerData.push({
                    key: each.id,
                    label: each.name,
                    index: i,
                });
            }
        }

        this.state = {
            keyword: this.props.navigation.getParam('keyword'),
            searchResults: [],

            apiPickerData: apiPickerData,
        }
    }

    componentDidMount(): void {
    }

    render() {
        return (
            <View style={{flex: 1}}>

                <MyStatusBar backgroundColor="#f4511e"/>

                <SearchInput
                    defaultValue={this.state.keyword}
                    onChangeText={(text) => {
                        this.setState({keyword: text});
                    }}
                    onCancel={() => {
                        this.props.navigation.goBack()
                    }}
                    onSubmitEditing={(text) => {
                        // this.search(this.state.keyword)
                        if (this.state.keyword === '') {
                            alert('搜索关键字不能留白');
                            return;
                        }
                        this.apiPicker.open();
                    }}
                />

                {this.renderSearchResults()}

                <ModalPicker
                    style={{height: 0}}
                    cancelText="关闭"
                    data={this.state.apiPickerData}
                    ref={picker => {
                        this.apiPicker = picker;
                    }}
                    initValue="Select something yummy!"
                    onChange={(_option) => {
                        this.search(this.state.keyword, _option.key);
                    }}
                />

                <MyLoading
                    ref={(ref) => {
                        global.mLoadingComponentRef = ref;
                    }}
                />
            </View>
        );
    }

    renderSearchResults = () => {
        return (
            <FlatList
                keyExtractor={(item, index) => 'index' + index}
                data={this.state.searchResults}
                renderItem={({item: rowData}) =>
                    <TouchableOpacity
                        activeOpacity={0.5}
                        onPress={() => {
                            this.props.navigation.navigate('Book', {book: rowData});
                        }}>
                        <BookItem {...rowData}/>
                        {/*<BookItem {...Object.assign(rowData, {add: true})}/>*/}

                    </TouchableOpacity>
                }
            />
        );
    };

    search = (keyword, usedApi) => {
        LoadingUtil.showLoading();
        ctx.search(keyword, usedApi)
            .then(books => {
                LoadingUtil.dismissLoading();
                this.setState({searchResults: books});
            })
            .catch(err => {
                LoadingUtil.dismissLoading();
                alert("搜索失败：" + err);
            })
        ;
    };
}


// 异常边界组件的使用
export default withErrorBoundary(SearchScreen, (error, errorInfo) => {
    console.log('errorCallback', error, errorInfo);
    alert("错误：" + errorInfo);
}, true);
